﻿#include "imageviewwidget.h"
#include "ui_imageviewwidget.h"

#include <utils/eventutil.h>

#include <imagehelper.h>
#include <QMainWindow>
#include <QMenu>
#include <QMessageBox>

ImageViewWidget::ImageViewWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ImageViewWidget)
    , m_movieing(false)
{
    ui->setupUi(this);
    setAcceptDrops(true);
}

ImageViewWidget::~ImageViewWidget()
{
    delete ui;
}

void ImageViewWidget::setFilePath(QString filePath)
{
    if (filePath.endsWith(".gif")) {
        ui->label->clear();
        ui->label->setMovie(&m_movie);
        m_movie.stop();
        m_movie.setFileName(filePath);
        m_movie.start();
        m_movieing = true;
        return;
    }
    m_movieing = false;
    this->setImage(QImage(filePath));
}

QImage ImageViewWidget::image() const
{
    return m_image;
}

void ImageViewWidget::setImage(const QImage &newImage)
{
    m_image = newImage;
    auto pixmap = QPixmap::fromImage(m_image);
    ui->label->setPixmap(ImageHelper::scaledKeepAspectRatio(ui->label->size(), pixmap));
}

void ImageViewWidget::dragEnterEvent(QDragEnterEvent *event)
{
    if (EventUtil::isDrageOneFileSuffix(event, ".png")) {
        event->accept();
    }
}

void ImageViewWidget::dropEvent(QDropEvent *event)
{
    setFilePath(EventUtil::getDropOneFileName(event));
}

void ImageViewWidget::on_actionClose_triggered()
{
    hide();
    emit onHiddend();
}

void ImageViewWidget::on_label_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu;
    menu.addAction(ui->actionClose);
    menu.exec(QCursor::pos());
}

void ImageViewWidget::resizeEvent(QResizeEvent *event)
{
    auto pixmap = QPixmap::fromImage(m_image);
    if (pixmap.isNull() && m_movieing == false) {
        ui->label->setText("将文件拖入显示，或拖入目录显示");
        return;
    }
    if (m_movieing == false)
        ui->label->setPixmap(ImageHelper::scaledKeepAspectRatio(ui->label->size(), pixmap));
}
